<template>
  <div class="page-container">
    <div class="page-content">
      <!-- 数据统计卡片 -->
      <div class="stats-cards">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ totalTags }}</div>
                <div class="stat-label">总话题数</div>
                <div class="stat-icon total">
                  <TagsOutlined />
                </div>
              </div>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ globalTags }}</div>
                <div class="stat-label">全局话题</div>
                <div class="stat-icon global">
                  <GlobalOutlined />
                </div>
              </div>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ pinnedTags }}</div>
                <div class="stat-label">置顶话题</div>
                <div class="stat-icon pinned">
                  <PushpinOutlined />
                </div>
              </div>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card class="stat-card">
              <div class="stat-content">
                <div class="stat-number">{{ totalUsage }}</div>
                <div class="stat-label">总使用次数</div>
                <div class="stat-icon usage">
                  <LineChartOutlined />
                </div>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </div>

      <!-- 图表展示区域 -->
      <div class="charts-section">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-card title="话题使用趋势" class="chart-card">
              <div ref="usageTrendChart" class="chart-container"></div>
            </a-card>
          </a-col>
          <a-col :span="12">
            <a-card title="话题类型分布" class="chart-card">
              <div ref="typeDistributionChart" class="chart-container"></div>
            </a-card>
          </a-col>
        </a-row>
        <a-row :gutter="16" style="margin-top: 16px">
          <a-col :span="24">
            <a-card title="热门话题排行" class="chart-card">
              <div ref="topTagsChart" class="chart-container-large"></div>
            </a-card>
          </a-col>
        </a-row>
      </div>

      <!-- 话题管理表格 -->
      <a-card>
        <!-- 搜索表单 -->
        <div class="search-form">
          <a-form layout="inline" :model="searchForm">
            <a-form-item label="话题名称">
              <a-input
                v-model:value="searchForm.postTagName"
                placeholder="请输入话题名称"
                style="width: 200px"
                allow-clear
                @pressEnter="handleSearch"
              />
            </a-form-item>
            <a-form-item label="话题类型">
              <a-select
                v-model:value="searchForm.isGlobal"
                placeholder="请选择话题类型"
                style="width: 150px"
                allow-clear
              >
                <a-select-option :value="1">全局话题</a-select-option>
                <a-select-option :value="0">学校话题</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="置顶状态">
              <a-select
                v-model:value="searchForm.isPinned"
                placeholder="请选择置顶状态"
                style="width: 120px"
                allow-clear
              >
                <a-select-option :value="1">已置顶</a-select-option>
                <a-select-option :value="0">未置顶</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="handleSearch">
                <SearchOutlined />
                查询
              </a-button>
              <a-button style="margin-left: 8px" @click="handleReset"> 重置 </a-button>
              <PermissionButton permission="circle:tag:add" style="margin-left: 8px">
                <a-button type="primary" @click="handleAdd">
                  <PlusOutlined />
                  新增话题
                </a-button>
              </PermissionButton>
            </a-form-item>
          </a-form>
        </div>

        <!-- 批量操作栏 -->
        <div v-if="selectedRowKeys.length > 0" class="batch-actions">
          <a-space>
            <span>已选择 {{ selectedRowKeys.length }} 项</span>
            <PermissionButton permission="circle:tag:pin">
              <a-button type="primary" size="small" @click="handleBatchPin">
                <PushpinOutlined />
                批量置顶
              </a-button>
            </PermissionButton>
            <PermissionButton permission="circle:tag:pin">
              <a-button size="small" @click="handleBatchUnpin"> 取消置顶 </a-button>
            </PermissionButton>
            <PermissionButton permission="circle:tag:delete">
              <a-button type="primary" size="small" danger @click="handleBatchDelete">
                <DeleteOutlined />
                批量删除
              </a-button>
            </PermissionButton>
            <a-button size="small" @click="clearSelection">取消选择</a-button>
          </a-space>
        </div>

        <!-- 表格 -->
        <a-table
          :columns="columns"
          :data-source="tableData"
          :loading="loading"
          :pagination="pagination"
          :row-selection="rowSelection"
          row-key="id"
          :scroll="{ x: 1200 }"
          @change="handleTableChange"
        >
          <!-- 话题名称 -->
          <template #tagName="{ record }">
            <div class="tag-name-cell">
              <a-tag color="blue" style="margin-bottom: 4px"> #{{ record.postTagName }} </a-tag>
              <div v-if="record.description" class="tag-description">
                {{ record.description }}
              </div>
            </div>
          </template>

          <!-- 话题类型 -->
          <template #tagType="{ record }">
            <a-tag :color="record.isGlobal === 1 ? 'gold' : 'green'">
              <GlobalOutlined v-if="record.isGlobal === 1" />
              <BankOutlined v-else />
              {{ record.isGlobal === 1 ? '全局话题' : '学校话题' }}
            </a-tag>
          </template>

          <!-- 使用统计 -->
          <template #usage="{ record }">
            <div class="usage-cell">
              <a-badge :count="record.usageCount" :number-style="{ backgroundColor: '#52c41a' }">
                <div class="usage-text">使用次数</div>
              </a-badge>
            </div>
          </template>

          <!-- 置顶状态 -->
          <template #pinStatus="{ record }">
            <div v-if="record.isPinned === 1" class="pin-status">
              <a-tag color="red">
                <PushpinOutlined />
                已置顶
              </a-tag>
              <div class="sort-info">
                <small>排序: {{ record.tagSort }}</small>
              </div>
            </div>
            <span v-else class="text-muted">普通</span>
          </template>

          <!-- 操作列 -->
          <template #action="{ record }">
            <div class="action-buttons">
              <PermissionButton permission="circle:tag:detail">
                <a-button
                  type="link"
                  size="small"
                  @click="handleViewDetail(record)"
                  class="action-btn"
                >
                  <EyeOutlined />
                </a-button>
              </PermissionButton>

              <PermissionButton permission="circle:tag:edit">
                <a-button type="link" size="small" @click="handleEdit(record)" class="action-btn">
                  <EditOutlined />
                </a-button>
              </PermissionButton>

              <PermissionButton permission="circle:tag:pin">
                <a-button
                  v-if="record.isPinned === 0"
                  type="link"
                  size="small"
                  @click="handlePin(record)"
                  class="action-btn"
                >
                  <PushpinOutlined />
                </a-button>
              </PermissionButton>

              <PermissionButton permission="circle:tag:pin">
                <a-button
                  v-if="record.isPinned === 1"
                  type="link"
                  size="small"
                  @click="handleUnpin(record)"
                  class="action-btn"
                >
                  <PushpinFilled />
                </a-button>
              </PermissionButton>

              <PermissionButton permission="circle:tag:delete">
                <a-popconfirm
                  title="确定要删除这个话题吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="handleDelete(record)"
                  placement="topRight"
                >
                  <a-button type="link" size="small" danger class="action-btn">
                    <DeleteOutlined />
                  </a-button>
                </a-popconfirm>
              </PermissionButton>
            </div>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 话题详情弹窗 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="话题详情"
      width="600px"
      :footer="null"
      :destroy-on-close="true"
    >
      <div v-if="currentTag" class="tag-detail">
        <div class="detail-header">
          <h3>#{{ currentTag.postTagName }}</h3>
          <div class="detail-meta">
            <a-tag :color="currentTag.isGlobal === 1 ? 'gold' : 'green'">
              {{ currentTag.isGlobal === 1 ? '全局话题' : '学校话题' }}
            </a-tag>
            <a-tag v-if="currentTag.isPinned === 1" color="red">
              <PushpinOutlined />
              已置顶
            </a-tag>
          </div>
        </div>

        <div class="detail-content">
          <div class="detail-item">
            <strong>话题描述：</strong>
            <p>{{ currentTag.description || '暂无描述' }}</p>
          </div>

          <div class="detail-stats">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-statistic title="使用次数" :value="currentTag.usageCount" />
              </a-col>
              <a-col :span="8">
                <a-statistic title="排序权重" :value="currentTag.tagSort" />
              </a-col>
              <a-col :span="8">
                <a-statistic
                  title="创建时间"
                  :value="formatDateTime(currentTag.createTime)"
                  :value-style="{ fontSize: '14px' }"
                />
              </a-col>
            </a-row>
          </div>
        </div>
      </div>
    </a-modal>

    <!-- 新增/编辑话题弹窗 -->
    <a-modal
      v-model:open="formModalVisible"
      :title="isEdit ? '编辑话题' : '新增话题'"
      width="500px"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :confirm-loading="submitLoading"
    >
      <a-form :model="formData" :rules="formRules" ref="formRef" layout="vertical">
        <a-form-item label="话题名称" name="postTagName">
          <a-input
            v-model:value="formData.postTagName"
            placeholder="请输入话题名称"
            :max-length="50"
            show-count
          />
        </a-form-item>

        <a-form-item label="话题描述" name="description">
          <a-textarea
            v-model:value="formData.description"
            placeholder="请输入话题描述"
            :rows="3"
            :max-length="200"
            show-count
          />
        </a-form-item>

        <a-form-item label="话题类型" name="isGlobal">
          <a-radio-group v-model:value="formData.isGlobal">
            <a-radio :value="0">学校话题</a-radio>
            <a-radio :value="1">全局话题</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="是否置顶" name="isPinned">
          <a-switch
            v-model:checked="pinnedChecked"
            checked-children="是"
            un-checked-children="否"
            @change="handlePinnedChange"
          />
        </a-form-item>

        <a-form-item v-if="pinnedChecked" label="排序权重" name="tagSort">
          <a-input-number
            v-model:value="formData.tagSort"
            :min="1"
            :max="999"
            placeholder="数字越小越靠前"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import {
  SearchOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  PushpinOutlined,
  PushpinFilled,
  TagsOutlined,
  GlobalOutlined,
  BankOutlined,
  LineChartOutlined,
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import type { PostTag, PostTagPageParams, PostTagRequest } from '@/types'
import { TagService } from '@/api/tag'
import PermissionButton from '@/components/PermissionButton.vue'
import { debounce } from '@/utils/debounce'

// 页面状态
const loading = ref(false)
const detailModalVisible = ref(false)
const formModalVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)
const currentTag = ref<PostTag | null>(null)
const selectedRowKeys = ref<number[]>([])

// 表单相关
const formRef = ref<FormInstance>()
const formData = reactive<PostTagRequest>({
  postTagName: '',
  description: '',
  isGlobal: 0,
  isPinned: 0,
  tagSort: 1,
})
const pinnedChecked = ref(false)

// 搜索表单
const searchForm = reactive({
  postTagName: '',
  isGlobal: undefined as number | undefined,
  isPinned: undefined as number | undefined,
})

// 表格数据
const tableData = ref<PostTag[]>([])

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条数据`,
})

// 图表引用
const usageTrendChart = ref<HTMLElement>()
const typeDistributionChart = ref<HTMLElement>()
const topTagsChart = ref<HTMLElement>()

// 统计数据状态
const overviewData = ref<any>({
  totalTags: 0,
  globalTags: 0,
  pinnedTags: 0,
  totalUsage: 0,
  typeDistribution: { global: 0, school: 0 },
  usageTrends: [],
})
const hotTagsData = ref<any[]>([])

// 统计数据计算（基于API返回的概览数据）
const totalTags = computed(() => overviewData.value.totalTags)
const globalTags = computed(() => overviewData.value.globalTags)
const pinnedTags = computed(() => overviewData.value.pinnedTags)
const totalUsage = computed(() => overviewData.value.totalUsage)

// 表单验证规则
const formRules = {
  postTagName: [
    { required: true, message: '请输入话题名称', trigger: 'blur' },
    { min: 1, max: 50, message: '话题名称长度为1-50个字符', trigger: 'blur' },
  ],
  description: [{ max: 200, message: '话题描述最多200个字符', trigger: 'blur' }],
  isGlobal: [{ required: true, message: '请选择话题类型', trigger: 'change' }],
  tagSort: [{ required: true, message: '请输入排序权重', trigger: 'blur' }],
}

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 60,
    fixed: 'left',
  },
  {
    title: '话题信息',
    key: 'tagName',
    width: 200,
    slots: { customRender: 'tagName' },
  },
  {
    title: '话题类型',
    key: 'tagType',
    width: 120,
    slots: { customRender: 'tagType' },
  },
  {
    title: '使用统计',
    key: 'usage',
    width: 120,
    slots: { customRender: 'usage' },
  },
  {
    title: '置顶状态',
    key: 'pinStatus',
    width: 120,
    slots: { customRender: 'pinStatus' },
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180,
    customRender: ({ text }: { text: string }) => formatDateTime(text),
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right',
    slots: { customRender: 'action' },
  },
]

// 行选择配置
const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: (keys: number[]) => {
    selectedRowKeys.value = keys
  },
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return dayjs(dateTime).format('YYYY-MM-DD HH:mm')
}

// 加载概览数据
const fetchOverviewData = async () => {
  try {
    const result = await TagService.getTagOverview()
    overviewData.value = result
  } catch (error) {
    console.error('获取话题概览数据失败:', error)
    message.error('获取话题概览数据失败')
  }
}

// 加载热门话题数据
const fetchHotTagsData = async () => {
  try {
    const result = await TagService.getHotTagRank()
    hotTagsData.value = result
  } catch (error) {
    console.error('获取热门话题数据失败:', error)
    message.error('获取热门话题数据失败')
  }
}

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    initUsageTrendChart()
    initTypeDistributionChart()
    initTopTagsChart()
  })
}

// 使用趋势图
const initUsageTrendChart = () => {
  if (!usageTrendChart.value) return

  const chart = echarts.init(usageTrendChart.value)
  const trends = overviewData.value.usageTrends || []

  const option = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#ccc',
      textStyle: { color: '#666' },
    },
    legend: {
      top: '5%',
      data: ['全局话题', '学校话题'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: trends.map((item: any) => item.date),
      axisLine: { lineStyle: { color: '#ddd' } },
      axisTick: { show: false },
      axisLabel: { color: '#666' },
    },
    yAxis: {
      type: 'value',
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: { color: '#666' },
      splitLine: { lineStyle: { color: '#f0f0f0' } },
    },
    series: [
      {
        name: '全局话题',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          color: '#1890ff',
          width: 3,
        },
        itemStyle: {
          color: '#1890ff',
          borderColor: '#fff',
          borderWidth: 2,
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(24, 144, 255, 0.3)' },
              { offset: 1, color: 'rgba(24, 144, 255, 0.05)' },
            ],
          },
        },
        data: trends.map((item: any) => item.globalUsage),
      },
      {
        name: '学校话题',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          color: '#52c41a',
          width: 3,
        },
        itemStyle: {
          color: '#52c41a',
          borderColor: '#fff',
          borderWidth: 2,
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(82, 196, 26, 0.3)' },
              { offset: 1, color: 'rgba(82, 196, 26, 0.05)' },
            ],
          },
        },
        data: trends.map((item: any) => item.schoolUsage),
      },
    ],
  }

  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
}

// 类型分布饼图
const initTypeDistributionChart = () => {
  if (!typeDistributionChart.value) return

  const chart = echarts.init(typeDistributionChart.value)
  const distribution = overviewData.value.typeDistribution || { global: 0, school: 0 }

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
    },
    legend: {
      bottom: '0%',
      left: 'center',
    },
    series: [
      {
        name: '话题类型',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '45%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: [
          {
            value: distribution.global,
            name: '全局话题',
            itemStyle: { color: '#faad14' },
          },
          {
            value: distribution.school,
            name: '学校话题',
            itemStyle: { color: '#52c41a' },
          },
        ],
      },
    ],
  }

  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
}

// 热门话题排行柱状图
const initTopTagsChart = () => {
  if (!topTagsChart.value) return

  const chart = echarts.init(topTagsChart.value)
  const topTags = hotTagsData.value.slice(0, 10) // 取前10个热门话题

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: { color: '#666' },
      splitLine: { lineStyle: { color: '#f0f0f0' } },
    },
    yAxis: {
      type: 'category',
      data: topTags.map((tag: any) => tag.tagName),
      axisLine: { lineStyle: { color: '#ddd' } },
      axisTick: { show: false },
      axisLabel: { color: '#666' },
    },
    series: [
      {
        name: '使用次数',
        type: 'bar',
        barWidth: '60%',
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              { offset: 0, color: '#1890ff' },
              { offset: 1, color: '#69c0ff' },
            ],
          },
          borderRadius: [0, 4, 4, 0],
        },
        data: topTags.map((tag: any) => tag.usageCount),
      },
    ],
  }

  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
}

// 加载数据 - 使用真实API
const fetchData = async () => {
  try {
    loading.value = true

    // 构建查询参数
    const params: PostTagPageParams = {
      page: pagination.current,
      pageSize: pagination.pageSize,
    }

    // 添加搜索条件
    if (searchForm.postTagName) {
      params.postTagName = searchForm.postTagName
    }
    if (searchForm.isGlobal !== undefined) {
      params.isGlobal = searchForm.isGlobal
    }
    if (searchForm.isPinned !== undefined) {
      params.isPinned = searchForm.isPinned
    }

    // 调用真实API获取数据
    const result = await TagService.getTagPage(params)
    tableData.value = result.result
    pagination.total = result.total
  } catch (error) {
    console.error('获取话题列表失败:', error)
    message.error('获取话题列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = debounce(() => {
  pagination.current = 1
  fetchData()
}, 500)

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    postTagName: '',
    isGlobal: undefined,
    isPinned: undefined,
  })
  pagination.current = 1
  fetchData()
}

// 表格分页变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchData()
}

// 查看详情
const handleViewDetail = async (record: PostTag) => {
  currentTag.value = record
  detailModalVisible.value = true
}

// 新增话题
const handleAdd = () => {
  isEdit.value = false
  Object.assign(formData, {
    postTagName: '',
    description: '',
    isGlobal: 0,
    isPinned: 0,
    tagSort: 1,
  })
  pinnedChecked.value = false
  formModalVisible.value = true
}

// 编辑话题
const handleEdit = (record: PostTag) => {
  isEdit.value = true
  Object.assign(formData, {
    id: record.id,
    postTagName: record.postTagName,
    description: record.description,
    isGlobal: record.isGlobal,
    isPinned: record.isPinned,
    tagSort: record.tagSort,
  })
  pinnedChecked.value = record.isPinned === 1
  formModalVisible.value = true
}

// 置顶状态变化
const handlePinnedChange = (checked: boolean) => {
  formData.isPinned = checked ? 1 : 0
  if (!checked) {
    formData.tagSort = undefined
  } else if (!formData.tagSort) {
    formData.tagSort = 1
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitLoading.value = true

    if (isEdit.value) {
      await TagService.updateTag(formData)
      message.success('编辑成功')
    } else {
      await TagService.createTag(formData)
      message.success('新增成功')
    }

    formModalVisible.value = false
    fetchData()
    // 刷新统计数据
    Promise.all([fetchOverviewData(), fetchHotTagsData()]).then(() => {
      initCharts()
    })
  } catch (error) {
    console.error('提交失败:', error)
    message.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 取消表单
const handleCancel = () => {
  formModalVisible.value = false
  formRef.value?.resetFields()
}

// 置顶话题
const handlePin = async (record: PostTag) => {
  try {
    await TagService.pinTag(record.id)
    message.success('置顶成功')
    fetchData()
    // 刷新统计数据
    fetchOverviewData()
  } catch (error) {
    console.error('置顶失败:', error)
    message.error('置顶失败')
  }
}

// 取消置顶
const handleUnpin = async (record: PostTag) => {
  try {
    await TagService.unpinTag(record.id)
    message.success('取消置顶成功')
    fetchData()
    // 刷新统计数据
    fetchOverviewData()
  } catch (error) {
    console.error('取消置顶失败:', error)
    message.error('取消置顶失败')
  }
}

// 删除话题
const handleDelete = async (record: PostTag) => {
  try {
    await TagService.deleteTag(record.id)
    message.success('删除成功')
    fetchData()
    // 刷新统计数据
    Promise.all([fetchOverviewData(), fetchHotTagsData()]).then(() => {
      initCharts()
    })
  } catch (error) {
    console.error('删除失败:', error)
    message.error('删除失败')
  }
}

// 批量置顶
const handleBatchPin = async () => {
  try {
    await TagService.batchPinTags(selectedRowKeys.value)
    message.success('批量置顶成功')
    clearSelection()
    fetchData()
    // 刷新统计数据
    fetchOverviewData()
  } catch (error) {
    console.error('批量置顶失败:', error)
    message.error('批量置顶失败')
  }
}

// 批量取消置顶
const handleBatchUnpin = async () => {
  try {
    await TagService.batchUnpinTags(selectedRowKeys.value)
    message.success('批量取消置顶成功')
    clearSelection()
    fetchData()
    // 刷新统计数据
    fetchOverviewData()
  } catch (error) {
    console.error('批量取消置顶失败:', error)
    message.error('批量取消置顶失败')
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await TagService.batchDeleteTags(selectedRowKeys.value)
    message.success('批量删除成功')
    clearSelection()
    fetchData()
    // 刷新统计数据
    Promise.all([fetchOverviewData(), fetchHotTagsData()]).then(() => {
      initCharts()
    })
  } catch (error) {
    console.error('批量删除失败:', error)
    message.error('批量删除失败')
  }
}

// 清除选择
const clearSelection = () => {
  selectedRowKeys.value = []
}

// 页面初始化
onMounted(() => {
  // 加载真实表格数据
  fetchData()

  // 加载统计数据
  Promise.all([fetchOverviewData(), fetchHotTagsData()]).then(() => {
    // 数据加载完成后初始化图表
    initCharts()
  })
})
</script>

<style scoped lang="scss">
.page-container {
  padding: 24px;
}

.stats-cards {
  margin-bottom: 24px;

  .stat-card {
    border-radius: 8px;
    overflow: hidden;

    :deep(.ant-card-body) {
      padding: 20px;
    }
  }

  .stat-content {
    position: relative;

    .stat-number {
      font-size: 28px;
      font-weight: bold;
      color: #1d1d1f;
      line-height: 1;
      margin-bottom: 8px;
    }

    .stat-label {
      font-size: 14px;
      color: #666;
    }

    .stat-icon {
      position: absolute;
      top: 0;
      right: 0;
      width: 48px;
      height: 48px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      color: white;

      &.total {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }

      &.global {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }

      &.pinned {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }

      &.usage {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      }
    }
  }
}

.charts-section {
  margin-bottom: 24px;

  .chart-card {
    border-radius: 8px;
    overflow: hidden;

    :deep(.ant-card-head) {
      border-bottom: 1px solid #f0f0f0;
    }
  }

  .chart-container {
    height: 280px;
    width: 100%;
  }

  .chart-container-large {
    height: 320px;
    width: 100%;
  }
}

.search-form {
  margin-bottom: 16px;
  padding: 24px;
  background: #fafafa;
  border-radius: 6px;
}

.batch-actions {
  margin-bottom: 16px;
  padding: 12px 16px;
  background: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 6px;
  color: #1890ff;
}

.tag-name-cell {
  .tag-description {
    margin-top: 4px;
    font-size: 12px;
    color: #999;
    line-height: 1.4;
  }
}

.usage-cell {
  display: flex;
  align-items: center;
  justify-content: center;

  .usage-text {
    font-size: 12px;
    color: #666;
    margin-left: 8px;
  }
}

.pin-status {
  .sort-info {
    margin-top: 4px;
    color: #999;
    font-size: 12px;
  }
}

.action-buttons {
  display: flex;
  gap: 4px;
  justify-content: flex-start;
  align-items: center;

  .action-btn {
    padding: 0 4px;
    height: 24px;
    line-height: 22px;
    min-width: 24px;

    .anticon {
      font-size: 12px;
    }
  }
}

.text-muted {
  color: #999;
  font-size: 12px;
}

.tag-detail {
  .detail-header {
    margin-bottom: 24px;

    h3 {
      margin-bottom: 12px;
      font-size: 18px;
      font-weight: 600;
      color: #1890ff;
    }

    .detail-meta {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }

  .detail-content {
    .detail-item {
      margin-bottom: 16px;

      strong {
        color: #333;
      }

      p {
        margin: 8px 0 0 0;
        color: #666;
        line-height: 1.6;
      }
    }

    .detail-stats {
      padding: 16px 0;
      border-top: 1px solid #f0f0f0;
      margin-top: 16px;
    }
  }
}
</style>